/*
 * @Author: spark
 * @Date: 2021-06-21 14:08:11
 * @LastEditTime: 2021-06-29 09:50:05
 * @LastEditors: spark
 * @Description: 一个持续与bug做抗争的程序员
 * email: spark.xiaoyu@qq.com
 */
import { ActionTypes } from './action-types'
import { PermissionsMutationsTypes } from './mutation-types'
import permissionRoutes from '@/router/permissionRoutes'
import constantRoutes from '@/router/constantRoutes'
import type { Mutations } from './mutations'
import { RouteRecordRaw } from 'vue-router';


const sleep = (t: number) => new Promise(resolve => setTimeout(resolve, t))


/**
 * @description: 判断是否有权限
 * @param {any} menus
 * @param {RouteRecordRaw} asyncRoutes
 * @return {*}
 */
function hasPermission(menus: any[], asyncRoutes: RouteRecordRaw) {
    // console.log(menus, 'menus')
    return menus.some((menu) => asyncRoutes.name == menu.resourceCode);
}


/**
 * @description: 筛选路由
 * @param {RouteRecordRaw} asyncRoutes
 * @param {any} menus
 * @return {*}
 */
export function filterAsyncRoutes(asyncRoutes: RouteRecordRaw[], menus?: any[]) {
    const accessedRouters = asyncRoutes.filter((route) => {
        if (menus && hasPermission(menus, route)) {
            if (route.children && route.children.length) {
                const find: RouteRecordRaw = menus.find(v => route.name == v.resourceCode);
                route.children = filterAsyncRoutes(
                    route.children,
                    find.children
                );
            }
            return true;
        }
        return false;
    });
    return accessedRouters;
    // return asyncRoutes
}


type AugmentedActionContext = {
    commit<K extends keyof Mutations>(
        key: K,
        payload?: Parameters<Mutations[K]>[1],
    ): ReturnType<Mutations[K]>
}

export type Actions = {
    [ActionTypes.ACTION_GENERATE_ROUTER]({ commit }: AugmentedActionContext): any
}
export const actions: Actions = {
    async [ActionTypes.ACTION_GENERATE_ROUTER]({ commit }) {
        await sleep(1000) //模拟网络延迟
        commit(PermissionsMutationsTypes['MUTATIONS_GET_PERMISSIONS'], [...constantRoutes, ...permissionRoutes])
    }
}
